import { message } from "antd";
import axios, {
  InternalAxiosRequestConfig,
  AxiosInstance,
  AxiosResponse,
  AxiosError,
} from "axios";
export const http: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 添加请求拦截器
http.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 在发送请求之前做些什么
    return config;
  },
  (error: any) => {
    // 处理请求错误
    return Promise.reject(error);
  }
);
http.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    if (response.data.code == 0) {
      message.error(response.data.msg);
      throw response.data.msg;
    }
    return response.data;
  },
  (error: AxiosError) => {
    // 处理响应错误
    const status = error.response?.status;
    switch (status) {
      case 400:
        error.message = "请求错误";
        break;
      case 403:
        error.message = "拒绝访问";
        break;
      case 404:
        error.message = "请求地址出错";
        break;
      case 408:
        error.message = "请求超时";
        break;
      case 500:
        error.message = "服务器内部错误";
        break;
      case 501:
        error.message = "服务未实现";
        break;
      case 502:
        error.message = "网关错误";
        break;
      case 503:
        error.message = "服务不可用";
        break;
      case 504:
        error.message = "网关超时";
        break;
      case 505:
        error.message = "HTTP 版本不受支持";
        break;
      default:
        break;
    }
    message.error(error.message);
    return Promise.reject(error);
  }
);
